<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @description 列表选择框、表格选择框
 * @author ThinkGem
-->
<template>
  <BasicModal
    v-bind="$attrs"
    :title="t('选择处理人')"
    @register="registerModal"
    @ok="handleSubmit"
    width="80%"
  >
    <ARow>
      <ACol :span="4" :style="getTreeStyle">
        <BasicTree
          :title="t('部门')"
          :search="true"
          :toolbar="true"
          :showIcon="true"
          :api="officeTreeData"
          :params="{ isAll: true }"
          :defaultExpandLevel="2"
          @select="handleTreeSelect"
        />
      </ACol>
      <ACol :span="17">
        <BasicTable
          @register="registerTable"
          @row-click="rowClick"
          @row-db-click="rowDbClick"
          :minHeight="treeHeight - 160"
        />
      </ACol>
      <ACol :span="3" class="pl-3 pt-4">
        {{ t('当前已选择') }} {{ selectList.length }} {{ t('项') }}：
        <div class="mt-2" v-if="selectList && selectList.length > 0">
          <Tag
            v-for="(item, index) in selectList"
            :key="item['userCode']"
            :closable="true"
            @close="closeTag(index)"
            color="#2a50ec"
          >
            {{ item['userName'] + ' (' + item['userCode'] + ')' }}
          </Tag>
        </div>
      </ACol>
    </ARow>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { computed, CSSProperties, ref } from 'vue';
  import { Row, Col, Tag } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicTree } from '/@/components/Tree';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTable, useTable, BasicTableProps, TableRowSelection } from '/@/components/Table';
  import { BasicColumn, FormProps } from '/@/components/Table';
  import { officeTreeData } from '/@/api/sys/office';
  import { empUserListData } from '/@/api/sys/empUser';
  import { useWindowSizeFn } from '/@/hooks/event/useWindowSizeFn';
  import { onMountedOrActivated } from '/@/hooks/core/onMountedOrActivated';

  const ARow = Row;
  const ACol = Col;

  const { t } = useI18n('listselect');
  const { showMessage } = useMessage();

  const treeHeight = ref(400);
  const getTreeStyle = computed((): CSSProperties => {
    return {
      height: `${treeHeight.value}px`,
      minHeight: `${treeHeight.value}px`,
    };
  });
  function calcTreeHeight() {
    let height = document.documentElement.clientHeight - 160;
    treeHeight.value = height;
  }
  useWindowSizeFn(calcTreeHeight, 280);
  onMountedOrActivated(calcTreeHeight);

  const searchForm: FormProps = {
    baseColProps: { lg: 8, md: 8 },
    labelWidth: 60,
    schemas: [
      {
        label: t('姓名'),
        field: 'refName',
        component: 'Input',
        componentProps: {
          onChange: () => {
            tableAction.reload();
          },
        },
      },
      {
        label: t('选择'),
        field: '_officeType',
        component: 'RadioGroup',
        componentProps: ({ tableAction, formModel }) => {
          return {
            options: [
              { label: '本部门', value: '1' },
              { label: '本公司', value: '2' },
            ],
            onChange: (v) => {
              if (v == '1') {
                formModel['employee.office.officeCode'] = currentOfficeCode.value;
                tableAction.reload();
              } else if (v == '2') {
                formModel['employee.office.officeCode'] = currentParentCode.value;
                tableAction.reload();
              }
            },
          };
        },
      },
      {
        label: t('机构'),
        field: 'employee.office.officeCode',
        component: 'Input',
        show: false,
      },
      {
        label: t('角色'),
        field: 'roleCode',
        component: 'Input',
        show: false,
      },
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('员工姓名'),
      dataIndex: 'refName',
      key: 'a.ref_name',
      sorter: true,
      width: 100,
    },
    {
      title: t('归属机构'),
      dataIndex: 'employee.office.officeName',
      key: 'o.office_name',
      sorter: true,
      width: 100,
    },
    {
      title: t('办公电话'),
      dataIndex: 'phone',
      key: 'a.phone',
      sorter: true,
      width: 130,
    },
    {
      title: t('状态'),
      dataIndex: 'status',
      key: 'a.status',
      sorter: true,
      width: 80,
      dictType: 'sys_status',
    },
  ];

  const emit = defineEmits(['select', 'register']);

  const selectList = ref<Recordable[]>([]);
  const checkbox = ref(false);
  const roleCode = ref('');
  const currentOfficeCode = ref('');
  const currentParentCode = ref('');

  const rowSelection: TableRowSelection = {
    type: 'checkbox',
    onChange: (_selectedRowKeys: string[], selectedRows: Recordable[]) => {
      selectList.value = selectedRows;
    },
  };

  const tableProps: BasicTableProps = {
    showTableSetting: false,
    useSearchForm: true,
    canResize: true,
    resizeHeightOffset: 100,
    api: empUserListData,
    beforeFetch: (params) => {
      params['isAll'] = true;
      params['roleCode'] = roleCode.value || '';
      return params;
    },
    immediate: true,
    columns: tableColumns,
    formConfig: searchForm,
    rowKey: 'userCode',
  };

  const [registerTable, tableAction] = useTable(tableProps);

  const [registerModal, { closeModal, setModalProps }] = useModalInner((data) => {
    //setModalProps({ loading: true });
    //console.log(data);

    checkbox.value = !!data.checkbox;
    tableAction.setProps({
      rowSelection: checkbox.value ? rowSelection : undefined,
    });

    roleCode.value = data.roleCode || '';

    currentOfficeCode.value = data.office?.officeCode || '';
    currentParentCode.value = data.office?.parentCode || '';

    setModalProps({ loading: false });
  });

  const rowClick = (record: Recordable) => {
    if (!checkbox.value) {
      selectList.value = [record];
    }
  };

  const rowDbClick = (record: Recordable) => {
    rowClick(record);
    if (!checkbox.value) {
      emit('select', [record]);
      closeModal();
    }
  };

  const closeTag = (index: number) => {
    selectList.value.splice(index, 1);
  };

  const handleSubmit = () => {
    if (selectList.value.length == 0) {
      showMessage('请选择下一步处理人');
      return;
    }
    emit('select', selectList.value);
    closeModal();
  };

  async function handleTreeSelect(keys: string[]) {
    const values = tableAction.getForm().getFieldsValue();
    values['employee.office.officeCode'] = keys[0] || '';
    await tableAction.getForm().setFieldsValue(values);
    await tableAction.reload();
  }
</script>
